<?php
namespace backend\controllers;

use Yii;
use yii\base\Exception;
use yii\web\AdminController;
use backend\models\UploadForm;
use backend\models\GoodsCategory;
use backend\models\HotSaleConfig;
use backend\models\BannerConfig;
use common\helps\tools;

class CategoryChildMaintainController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'CategoryChildMaintain';
    
    public $type = 2;
    
    public function actionIndex()
    {
        $model = new UploadForm();
        $category = GoodsCategory::find()->select('id,category_name')->where('parent_id=0')->asArray()->all();
        return $this->render('index',['model'=>$model,'category'=>$category]);
    }
    
    public function actionGetCategoryChildMaintain(){
        $data = Yii::$app->request->post();
        try{
            $type = $this->type;
            $query = HotSaleConfig::find()->select('id,sort,category_id,category_child,platform,use_flg')->where('type='.$type)->orderBy('use_flg desc,edit_time desc');
            $category_id = $data['category_id'];
            if ($category_id){
                $query = $query->andWhere('category_id=:category_id',[':category_id'=>$category_id]);
            }
            $count = $query->count();
            $list = $query->offset($data['start'])->limit($data['length'])->asArray()->all();
            $result_val = [];
            if (count($list) > 0){
                $id = array_column($list, 'id');
                //将一级目录和二级目录从二位数组中抓取出来并将返回的数据合并到新的数组中
                $category_id = array_unique(array_filter(array_column($list, 'category_id')));
                $category_child = array_unique(array_filter(array_column($list, 'category_child')));
                $category_list = array_unique(array_merge($category_id,$category_child));
                if (count($category_list) > 0){
                    $category = GoodsCategory::find()->select('id,category_name')->where(['in','id',$category_list])->asArray()->all();
                    if (count($category) > 0){
                        $category_val = array_combine(array_column($category, 'id'), $category);
                    }
                }
                $banner_config = BannerConfig::find()->where(['in','group_id',$id])->asArray()->all();
                $banner_config_arr = [];
                if (is_array($banner_config) && count($banner_config) > 0)foreach ($banner_config as $banner){
                    $banner_config_arr[$banner['group_id']][] = $banner;
                }
                foreach ($list as $val){
                    $val['category_name'] = $val['category_id'] && tools::arrayHasValue($category_val,$val['category_id']) && tools::arrayHasValue($category_val[$val['category_id']],'category_name') ? $category_val[$val['category_id']]['category_name'] : '';
                    $val['category_child_name'] = $val['category_child'] && tools::arrayHasValue($category_val,$val['category_child']) && tools::arrayHasValue($category_val[$val['category_child']],'category_name') ? $category_val[$val['category_child']]['category_name'] : '';
                    $val['banner_config'] = tools::arrayHasValue($banner_config_arr,$val['id']) ? $banner_config_arr[$val['id']] : [];
                    $result_val[] = $val;
                }
            }
            $result['draw'] = intval($data['draw']);
            $result['recordsTotal'] = intval($count);
            $result['recordsFiltered'] = intval($count);
            $result['data'] = $result_val;
            return \yii\helpers\Json::encode($result);
        }catch (Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($ex->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            return '';
        }
    }
    
    public function actionChangeCategoryChildMaintainSort(){
        $model = new HotSaleConfig();
        $data = Yii::$app->request->post();
        $id = $data['id'];
        $sort = $data['sort'];
        $data_new = [
            'sort'=>$sort,
            'editor'=>$model->getCreator(),
            'edit_time'=>date('Y-m-d H:i:s')
        ];
        $ret = $model::updateAll($data_new,['id'=>$id]);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $this->retJson('操作成功',200);
    }
    
    public function actionChangeCategoryChildMaintainStatus(){
        $model = new HotSaleConfig();
        $data = Yii::$app->request->post();
        $id = $data['id'];
        $use_flg = $data['use_flg'];
        $data_new = [
            'use_flg'=>$use_flg,
            'editor'=>$model->getCreator(),
            'edit_time'=>date('Y-m-d H:i:s')
        ];
        $ret = $model::updateAll($data_new,['id'=>$id]);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $this->retJson('操作成功',200);
    }
    
    public function actionGetCategoryChild(){
        $data = Yii::$app->request->post();
        $category_id = $data['category_id'];
        $category_child = GoodsCategory::find()->select('id,category_name')->where(
            'parent_id=:parent_id',[':parent_id'=>$category_id])->asArray()->all();
        $this->retJson($category_child,200);
    }
    
    public function actionCategoryChildMaintainDetail(){
        $data = Yii::$app->request->post();
        $id = $data['id'];
        $category_child = HotSaleConfig::find()->select(
            'id,sort,category_id,category_child,platform,use_flg'
        )->where('type=2 and id=:id',[':id'=>$id])->asArray()->one();
        if (count($category_child) > 0){
            $category_id = $category_child['category_id'];
            $category_child_id = $category_child['category_child'];
            if ($category_id || $category_child_id){
                $category_ids = [$category_id,$category_child_id];
                $category_ids = array_filter($category_ids);
                $category_name = GoodsCategory::find()->select('id,category_name')->where(['in','id',$category_ids])->asArray()->all();
                $category_name = array_combine(array_column($category_name, 'id'), $category_name);
            }
            $banner_config = BannerConfig::find()->select(
                'id,group_id,picture_name,picture_url,product_url,ext2')->where('group_id='.$id)->orderBy('sort asc')->asArray()->all();
            $category_child['category_name'] = $category_child['category_id'] && tools::arrayHasValue($category_name,$category_child['category_id']) && tools::arrayHasValue($category_name[$category_child['category_id']],'category_name') ? $category_name[$category_child['category_id']]['category_name'] : '';
            $category_child['category_child_name'] = $category_child['category_child'] && tools::arrayHasValue($category_name,$category_child['category_child']) && tools::arrayHasValue($category_name[$category_child['category_child']],'category_name') ? $category_name[$category_child['category_child']]['category_name'] : '';
            $category_child['banner_config'] = $banner_config;
        }
        $this->retJson($category_child,200);
    }
    
    public function actionChangeCategoryChildMaintain(){
        $model = new HotSaleConfig();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $oper = $model->getCreator();
            $oper_time = date('Y-m-d H:i:s');
            $platform = $data['platform'];
            $hot_sale_id = $data['hot_sale_id'];
            $category_id = $data['category_id'];
            $use_flg = $data['use_flg'];
            $ext2 = $data['ext2'];
            $type = $this->type;
            $sort = '';
            if (!$category_id){
                throw new \Exception('请选择一级分类');
            }
            $category_name = GoodsCategory::find()->select('category_name')->where('id=:id',[':id'=>$category_id])->asArray()->one();
            if (!$category_name['category_name']) {
                throw new \Exception('一级分类不存在');
            }
            $category_child = '';
            $banner_config_id = $picture_url = $product_url = [];
            if($category_name['category_name'] == '奢品'){
                $category_child = $data['category_child'];
                if (!$category_child){
                    throw new \Exception('请选择二级分类');
                }
                $banner_config_id = $data['banner_config_id'];
                $picture_url = $data['picture_url'];
                $product_url = $data['product_url'];
                if (count(array_filter($picture_url)) == 0){
                    throw new \Exception('至少填写一个图片信息');
                }
            }else{
                $sort = $data['sort'];
                if (!$sort){
                    throw new \Exception('请填写二级分类排序编号');
                }
                $picture_url = $data['picture_url_dan'];
                if (!$picture_url){
                    throw new \Exception('请上传一张商品图片');
                }
                $product_name = $data['product_url_dan'];
                if (!$product_name){
                    throw new \Exception('请填写点击链接');
                }
            }
            $bannerAll = new BannerConfig();
            $banner_ids = [];
            if ($hot_sale_id){
                $model = HotSaleConfig::findOne($hot_sale_id);
                $model->editor = $oper;
                $model->edit_time = $oper_time;
                $where_banner['group_id'] = $hot_sale_id;
                if ($category_name['category_name'] == '奢品'){
                    $bannerAll = BannerConfig::find()->where($where_banner)->asArray()->all();
                    $banner_ids = array_column($bannerAll, 'id');
                }else{
                    $bannerAll = BannerConfig::find()->where($where_banner)->one();
                }
            }else{
                $model->creator = $oper;
                $model->create_time = $oper_time;
                $model->type = $type;
            }
            if ($sort){
                $model->sort = $sort;
            }
            $model->platform = $platform;
            $model->category_id = $category_id;
            $model->category_child = $category_child;
            $model->use_flg = $use_flg;
            $model->save();
            $hot_sale_new_id = $model->attributes['id'];
            if (!$hot_sale_new_id){
                throw new \Exception('二级分类维护失败');
            }
            $sort = 1;
            if (count($banner_config_id) > 0)for ($i=0;$i<count($banner_config_id);$i++){
                if (!$picture_url[$i] || !$product_url[$i]) continue;
                $banner = new BannerConfig();
                if ($banner_config_id[$i]){
                    $banner = $banner->findOne($banner_config_id[$i]);
                    $banner->editor = $oper;
                    $banner->edit_time = $oper_time;
                }else{
                    $banner->creator = $oper;
                    $banner->create_time = $oper_time;
                }
                $banner->group_id = $hot_sale_new_id;
                $banner->product_url = $product_url[$i];
                $banner->sort = $sort;
                $banner->picture_url = $picture_url[$i];
                $banner->save();
                $banner_id = $banner->attributes['id'];
                if (!$banner_id){
                    throw new \Exception('热销商品明细操作失败');
                }
                $sort++;
            }
            if ($category_name['category_name'] == '奢品'){
                if (is_array($banner_ids) && count($banner_ids))foreach ($banner_ids as $bannerId){
                    if (!in_array($bannerId,$banner_config_id)){
                        $bannerDel = BannerConfig::deleteAll(['id'=>$bannerId]);
                        if(!$bannerDel){
                            throw new \Exception('操作失败');
                        }
                    }
                }
            }else{
                $bannerAll->group_id = $hot_sale_new_id;
                $bannerAll->ext2 = $ext2;
                $bannerAll->picture_url = $picture_url;
                $bannerAll->product_url = $product_name;
                $bannerAll->save();
                $banner_id = $bannerAll->attributes['id'];
                if (!$banner_id){
                    throw new \Exception('操作失败');
                }
            }
            $transaction->commit();
            $this->retJson('编辑成功',200);
        } catch (\Exception $e) {
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            $transaction->rollBack();
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
        
        
    }
}